from django.shortcuts import render

# Create your views here.
import os
import time
import random
from django.http import JsonResponse
from rest_framework.views import APIView
from django.conf import settings
from django.core.files.storage import default_storage
from django.utils.timezone import now
from login.views import verify_token  # 假设已经有验证 token 的函数
import platform

class FileUploadView(APIView):
    def post(self, request, *args, **kwargs):
        # 获取 Authorization 令牌并验证
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        try:
            # 获取上传的文件
            uploaded_file = request.FILES.get('file')
            if not uploaded_file:
                return JsonResponse({
                    'code': '10006',
                    'msg': '未检测到文件'
                }, status=400)

            # 生成基于年月日的目录
            upload_date = now().strftime('%Y/%m/%d')
            upload_dir = os.path.join(settings.MEDIA_ROOT, upload_date)

            if not os.path.exists(upload_dir):
                os.makedirs(upload_dir)

            # 生成唯一文件名
            file_name = f"{int(time.time())}_{random.randint(1000, 9999)}{os.path.splitext(uploaded_file.name)[1]}"
            file_path = os.path.join(upload_dir, file_name)

            # 保存文件
            file_url = default_storage.save(file_path, uploaded_file)

            # 构造文件 URL
            file_url = settings.BASE_URL + os.path.join(settings.MEDIA_URL, upload_date, file_name).replace('\\', '/')

            return JsonResponse({
                'code': '00000',
                'data': {
                    'name': uploaded_file.name,
                    'url': file_url
                },
                'msg': '文件上传成功'
            }, status=200)

        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'未知错误: {str(e)}'
            }, status=500)

    def delete(self, request, *args, **kwargs):
        # 获取 Authorization 令牌
        auth_header = request.headers.get('Authorization')
        if not auth_header or not auth_header.startswith('Bearer '):
            return JsonResponse({
                'code': '10004',
                'msg': '无效的令牌'
            }, status=401)

        access_token = auth_header.split(' ')[1]  # 获取实际的 JWT 令牌

        # 验证令牌有效性
        payload = verify_token(access_token)
        if 'error' in payload:
            return JsonResponse({
                'code': '10005',
                'msg': '令牌验证失败'
            }, status=401)

        # 获取文件路径参数
        file_path = request.GET.get('filePath')
        if not file_path:
            return JsonResponse({
                'code': '10006',
                'msg': '文件路径不能为空'
            }, status=400)

        # 去除URL部分，只保留相对路径
        if 'media/' in file_path:
            file_path = file_path.split('media/', 1)[-1]  # 只保留 'media/' 之后的相对路径

        # 判断当前操作系统是否是 Windows
        if platform.system().lower() == 'windows':
            # 如果是 Windows 系统，替换路径中的正斜杠为反斜杠
            file_path = file_path.replace('/', '\\')

        # 计算完整的文件路径
        absolute_file_path = os.path.join(settings.MEDIA_ROOT, file_path)

        print(absolute_file_path)  # 调试用，确保路径正确

        # 检查文件是否存在
        if not os.path.exists(absolute_file_path):
            return JsonResponse({
                'code': '10007',
                'msg': '文件不存在'
            }, status=404)

        # 删除文件
        try:
            os.remove(absolute_file_path)
            return JsonResponse({
                'code': '00000',
                'msg': '文件删除成功'
            }, status=200)
        except Exception as e:
            return JsonResponse({
                'code': '10008',
                'msg': f'文件删除失败: {str(e)}'
            }, status=500)
